import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:raze/artifacts/notifier_glimmer.dart';
import 'package:raze/artifacts/clickable_avatar_widget.dart';
import 'package:raze/artifacts/report_vault_dialog.dart';
import 'package:raze/lore/chronicle/community_chronicle.dart';
import 'package:raze/lore/chronicle/qna_chronicle.dart';
import 'package:raze/lore/chronicle/user_chronicle.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';

/// 查询宝库页面 - 搜索问答和社区内容
class QueryVaultRealms extends StatefulWidget {
  const QueryVaultRealms({super.key});

  @override
  State<QueryVaultRealms> createState() => _QueryVaultRealmsState();
}

class _QueryVaultRealmsState extends State<QueryVaultRealms>
    with SingleTickerProviderStateMixin {
  late TabController _tabNavigator;
  final TextEditingController _queryTextCaster = TextEditingController();
  final FocusNode _queryFocusSentry = FocusNode();

  // 获取传递的初始搜索文本
  String? get _initialQueryPhrase => Get.parameters['query'];

  @override
  void initState() {
    super.initState();
    _tabNavigator = TabController(length: 2, vsync: this);

    // 设置初始搜索文本
    if (_initialQueryPhrase != null && _initialQueryPhrase!.isNotEmpty) {
      _queryTextCaster.text = _initialQueryPhrase!;
    }
  }

  @override
  void dispose() {
    _tabNavigator.dispose();
    _queryTextCaster.dispose();
    _queryFocusSentry.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final qnaChronicle = Get.find<QnAChronicle>();
    final communityChronicle = Get.find<CommunityChronicle>();
    final userChronicle = Get.find<UserChronicle>();

    return GestureDetector(
      onTap: () {
        // 点击空白区域取消焦点
        if (_queryFocusSentry.hasFocus) {
          _queryFocusSentry.unfocus();
        }
      },
      child: Scaffold(
        body: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/background.png'),
              fit: BoxFit.cover,
            ),
          ),
          child: SafeArea(
            bottom: false,
            child: Column(
              children: [
                // 顶部标题栏
                _buildTopNavigationBar(),
                16.h.boxHeight,

                // 搜索框
                _buildQueryInputField(),
                20.h.boxHeight,

                // Tab 切换栏
                _buildTabSwitcher(),
                16.h.boxHeight,

                // 搜索结果内容
                Expanded(
                  child: TabBarView(
                    controller: _tabNavigator,
                    children: [
                      // 问答搜索结果
                      _buildQuestionsResultsPanel(qnaChronicle, userChronicle),
                      // 社区搜索结果
                      _buildCommunityResultsPanel(
                        communityChronicle,
                        userChronicle,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        children: [
          // 返回按钮
          Container(
                width: 30.w,
                height: 30.w,
                decoration: BoxDecoration(
                  color: RazeConstants.white,
                  borderRadius: BorderRadius.circular(12.r),
                  border: Border.all(color: RazeConstants.black, width: 1.5.w),
                ),
                child: Icon(
                  Icons.chevron_left_rounded,
                  size: 24.sp,
                  color: RazeConstants.black,
                ),
              )
              .withRightBottomShadow(thickness: 1)
              .withTouchResonance(onTap: () => Get.back()),

          // 标题
          Expanded(
            child: Center(
              child: Text('Search')
                  .applyTypeSize(24.sp)
                  .applyTypeColor(RazeConstants.black)
                  .applyBagelFatOne(weight: FontWeight.w400),
            ),
          ),
          36.w.boxWidth,
        ],
      ),
    );
  }

  /// 构建搜索输入框
  Widget _buildQueryInputField() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 15.w),
        height: 55.h,
        decoration: BoxDecoration(
          color: RazeConstants.white,
          borderRadius: BorderRadius.circular(20.r),
          border: Border.all(color: RazeConstants.black, width: 1.5.w),
        ),
        child: Row(
          children: [
            Image.asset('assets/images/search.png', width: 20.w, height: 20.w),
            12.w.boxWidth,
            Expanded(
              child: TextField(
                controller: _queryTextCaster,
                focusNode: _queryFocusSentry,
                onChanged: (value) {
                  setState(() {}); // 触发搜索结果更新
                },
                decoration: InputDecoration(
                  hintText: 'Search For Questions, Updates',
                  hintStyle: TextStyle(
                    color: RazeConstants.black.withOpacity(0.4),
                    fontSize: 12.sp,
                    fontWeight: FontWeight.w400,
                  ),
                  border: InputBorder.none,
                  isDense: true,
                  contentPadding: EdgeInsets.zero,
                ),
                style: TextStyle(
                  color: RazeConstants.black,
                  fontSize: 12.sp,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
            // 清除按钮
            if (_queryTextCaster.text.isNotEmpty)
              GestureDetector(
                onTap: () {
                  setState(() {
                    _queryTextCaster.clear();
                  });
                },
                child: Icon(
                  Icons.clear,
                  size: 20.w,
                  color: RazeConstants.black.withOpacity(0.5),
                ),
              ),
          ],
        ),
      ).withRightBottomShadow(thickness: 1.5),
    );
  }

  /// 构建 Tab 切换栏
  Widget _buildTabSwitcher() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Container(
        height: 45.h,
        decoration: BoxDecoration(
          color: RazeConstants.white,
          borderRadius: BorderRadius.circular(14.r),
          border: Border.all(color: RazeConstants.black, width: 1.5.w),
        ),
        child: TabBar(
          controller: _tabNavigator,
          indicator: BoxDecoration(
            color: RazeConstants.yellow,
            borderRadius: BorderRadius.circular(12.r),
          ),
          indicatorSize: TabBarIndicatorSize.tab,
          labelColor: RazeConstants.black,
          unselectedLabelColor: RazeConstants.black.withOpacity(0.5),
          labelStyle: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.w400,
            fontFamily:
                GoogleFonts.bagelFatOne(fontWeight: FontWeight.w300).fontFamily,
          ),
          unselectedLabelStyle: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.w400,
            fontFamily:
                GoogleFonts.bagelFatOne(fontWeight: FontWeight.w400).fontFamily,
          ),
          dividerColor: Colors.transparent,
          tabs: const [Tab(text: 'questions'), Tab(text: 'updates')],
        ),
      ).withRightBottomShadow(thickness: 1.5),
    );
  }

  /// 构建问答搜索结果面板
  Widget _buildQuestionsResultsPanel(
    QnAChronicle qnaChronicle,
    UserChronicle userChronicle,
  ) {
    return Obx(() {
      final queryPhrase = _queryTextCaster.text.toLowerCase().trim();

      // 模糊搜索：搜索内容包含关键词的问题
      final filteredQuestions =
          queryPhrase.isEmpty
              ? qnaChronicle.questionList
              : qnaChronicle.questionList.where((question) {
                return question.content.toLowerCase().contains(queryPhrase);
              }).toList();

      if (filteredQuestions.isEmpty) {
        return _buildEmptyResultsWidget('No questions found');
      }

      return ListView.builder(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        itemCount: filteredQuestions.length,
        itemBuilder: (context, index) {
          final question = filteredQuestions[index];
          final user = userChronicle.userList.firstWhereOrNull(
            (u) => u.id == question.userId,
          );
          final answerCount =
              qnaChronicle.fetchAnswersByQuestionId(question.id).length;

          return _buildQuestionItemCard(
            question: question,
            user: user,
            answerCount: answerCount,
            qnaChronicle: qnaChronicle,
            userChronicle: userChronicle,
          );
        },
      );
    });
  }

  /// 构建社区搜索结果面板
  Widget _buildCommunityResultsPanel(
    CommunityChronicle communityChronicle,
    UserChronicle userChronicle,
  ) {
    return Obx(() {
      final queryPhrase = _queryTextCaster.text.toLowerCase().trim();

      // 模糊搜索：搜索详情包含关键词的社区帖子
      final filteredCommunities =
          queryPhrase.isEmpty
              ? communityChronicle.communityList
              : communityChronicle.communityList.where((community) {
                return community.detail.toLowerCase().contains(queryPhrase);
              }).toList();

      if (filteredCommunities.isEmpty) {
        return _buildEmptyResultsWidget('No updates found');
      }

      return ListView.builder(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        itemCount: filteredCommunities.length,
        itemBuilder: (context, index) {
          final community = filteredCommunities[index];
          final user = userChronicle.userList.firstWhereOrNull(
            (u) => u.id == community.userId,
          );

          return _buildCommunityItemCard(
            community: community,
            user: user,
            communityChronicle: communityChronicle,
            userChronicle: userChronicle,
          );
        },
      );
    });
  }

  /// 构建空结果提示组件
  Widget _buildEmptyResultsWidget(String message) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            'assets/images/empty-status.png',
            width: 120.w,
            height: 120.w,
          ),
          16.h.boxHeight,
          Text(message)
              .applyTypeSize(16.sp)
              .applyTypeColor(RazeConstants.black.withOpacity(0.6))
              .applyNotoSans(weight: FontWeight.w500),
        ],
      ),
    );
  }

  /// 构建问题卡片项
  Widget _buildQuestionItemCard({
    required dynamic question,
    required dynamic user,
    required int answerCount,
    required QnAChronicle qnaChronicle,
    required UserChronicle userChronicle,
  }) {
    final questionId = question.id;
    final currentUser = userChronicle.currentUser;
    final isLoggedIn = userChronicle.isLoggedIn;

    return Obx(() {
      final questions = qnaChronicle.questionList;
      final current =
          questions.firstWhereOrNull((q) => q.id == questionId) ?? question;
      final liked =
          isLoggedIn && currentUser != null
              ? qnaChronicle.checkQuestionLiked(currentUser.id, questionId)
              : false;
      final likeColor = liked ? RazeConstants.red : RazeConstants.black;

      return Container(
        margin: EdgeInsets.only(bottom: 16.h),
        padding: EdgeInsets.all(14.w),
        decoration: BoxDecoration(
          color: RazeConstants.white,
          borderRadius: BorderRadius.circular(16.r),
          border: Border.all(color: RazeConstants.black, width: 1.5.w),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户信息行
            Row(
              children: [
                // 用户头像
                if (user != null)
                  ClickableAvatarWidget(
                    userId: user.id,
                    avatarPath: user.avatar,
                    width: 32.w,
                    height: 32.w,
                  ),
                if (user != null) 10.w.boxWidth,
                // 用户名
                Expanded(
                  child: Text(user?.username ?? 'Unknown')
                      .applyTypeSize(14.sp)
                      .applyTypeColor(RazeConstants.black)
                      .applyNotoSans(weight: FontWeight.w600),
                ),
                // 举报按钮
                GestureDetector(
                  onTap: () {
                    ReportVaultDialog.revealReportVault(
                      onReportSubmitted: (_) {
                        // 举报成功提示
                        NotifierGlimmer.revealInfo(
                          'Reported submitted successfully.',
                        );
                        // 删除被举报的问题
                        qnaChronicle.deleteQuestionById(questionId);
                      },
                    );
                  },
                  child: Image.asset(
                    'assets/images/report.png',
                    width: 20.w,
                    height: 20.w,
                  ),
                ),
              ],
            ),
            12.h.boxHeight,
            // 问题内容
            Text(current.content)
                .applyTypeSize(14.sp)
                .applyTypeColor(RazeConstants.black)
                .applyNotoSans(),
            12.h.boxHeight,
            // 底部操作栏
            Row(
              children: [
                // 点赞按钮
                Row(
                  children: [
                    Image.asset(
                      'assets/images/like.png',
                      width: 18.w,
                      height: 18.w,
                      color: likeColor,
                    ),
                    6.w.boxWidth,
                    Text('${current.likeCount}')
                        .applyTypeSize(14.sp)
                        .applyTypeColor(RazeConstants.black)
                        .applyNotoSans(weight: FontWeight.w600),
                  ],
                ).withTouchResonance(
                  onTap: () {
                    if (!isLoggedIn) {
                      return;
                    }
                    if (currentUser != null) {
                      if (liked) {
                        qnaChronicle.unlikeQuestion(currentUser.id, questionId);
                      } else {
                        qnaChronicle.likeQuestion(currentUser.id, questionId);
                      }
                    }
                  },
                ),
                20.w.boxWidth,
                // 回答数量
                Row(
                  children: [
                    Image.asset(
                      'assets/images/message-text.png',
                      width: 18.w,
                      height: 18.w,
                      color: RazeConstants.black,
                    ),
                    6.w.boxWidth,
                    Text('$answerCount')
                        .applyTypeSize(14.sp)
                        .applyTypeColor(RazeConstants.black)
                        .applyNotoSans(weight: FontWeight.w600),
                  ],
                ),
              ],
            ),
          ],
        ),
      ).withRightBottomShadow(thickness: 1.5);
    });
  }

  /// 构建社区卡片项
  Widget _buildCommunityItemCard({
    required dynamic community,
    required dynamic user,
    required CommunityChronicle communityChronicle,
    required UserChronicle userChronicle,
  }) {
    final communityId = community.id;
    final currentUser = userChronicle.currentUser;
    final isLoggedIn = userChronicle.isLoggedIn;

    return Obx(() {
      final communities = communityChronicle.communityList;
      final current =
          communities.firstWhereOrNull((c) => c.id == communityId) ?? community;
      final liked =
          isLoggedIn && currentUser != null
              ? communityChronicle.checkCommunityLiked(
                currentUser.id,
                communityId,
              )
              : false;
      final likeColor = liked ? RazeConstants.red : RazeConstants.black;
      final commentCount = communityChronicle.fetchComments(communityId).length;

      return Container(
        margin: EdgeInsets.only(bottom: 16.h),
        decoration: BoxDecoration(
          color: RazeConstants.white,
          borderRadius: BorderRadius.circular(16.r),
          border: Border.all(color: RazeConstants.black, width: 1.5.w),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户信息
            Padding(
              padding: EdgeInsets.all(14.w),
              child: Row(
                children: [
                  // 用户头像
                  if (user != null)
                    ClipOval(
                      child: Image.asset(
                        user.avatar,
                        width: 32.w,
                        height: 32.w,
                        fit: BoxFit.cover,
                      ),
                    ),
                  if (user != null) 10.w.boxWidth,
                  // 用户名
                  Expanded(
                    child: Text(user?.username ?? 'Unknown')
                        .applyTypeSize(14.sp)
                        .applyTypeColor(RazeConstants.black)
                        .applyNotoSans(weight: FontWeight.w600),
                  ),
                  // 举报按钮
                  GestureDetector(
                    onTap: () {
                      ReportVaultDialog.revealReportVault(
                        onReportSubmitted: (_) {
                          // 举报成功提示
                          NotifierGlimmer.revealInfo(
                            'Reported submitted successfully.',
                          );
                          // 删除被举报的社区帖子
                          communityChronicle.deleteCommunityById(communityId);
                        },
                      );
                    },
                    child: Image.asset(
                      'assets/images/report.png',
                      width: 20.w,
                      height: 20.w,
                    ),
                  ),
                ],
              ),
            ),
            // 媒体内容
            if (community.contentType == 'image')
              ClipRRect(
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(0),
                  topRight: Radius.circular(0),
                ),
                child: Image.asset(
                  community.media,
                  width: double.infinity,
                  height: 200.h,
                  fit: BoxFit.cover,
                ),
              ),
            // 视频封面
            if (community.contentType == 'video')
              Stack(
                alignment: Alignment.center,
                children: [
                  ClipRRect(
                    borderRadius: const BorderRadius.only(
                      topLeft: Radius.circular(0),
                      topRight: Radius.circular(0),
                    ),
                    child: Image.asset(
                      community.coverImage ?? '',
                      width: double.infinity,
                      height: 200.h,
                      fit: BoxFit.cover,
                    ),
                  ),
                  // 播放图标
                  Container(
                    width: 56.w,
                    height: 56.w,
                    decoration: BoxDecoration(
                      color: RazeConstants.white.withOpacity(0.9),
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: RazeConstants.black,
                        width: 2.w,
                      ),
                    ),
                    child: Icon(
                      Icons.play_arrow_rounded,
                      size: 36.w,
                      color: RazeConstants.black,
                    ),
                  ).withRightBottomShadow(thickness: 1.5),
                ],
              ),
            // 详情文本
            Padding(
              padding: EdgeInsets.all(14.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(current.detail)
                      .applyTypeSize(14.sp)
                      .applyTypeColor(RazeConstants.black)
                      .applyNotoSans(),
                  12.h.boxHeight,
                  // 底部操作栏
                  Row(
                    children: [
                      // 点赞按钮
                      Row(
                        children: [
                          Image.asset(
                            'assets/images/like.png',
                            width: 18.w,
                            height: 18.w,
                            color: likeColor,
                          ),
                          6.w.boxWidth,
                          Text('${current.likeCount}')
                              .applyTypeSize(14.sp)
                              .applyTypeColor(RazeConstants.black)
                              .applyNotoSans(weight: FontWeight.w600),
                        ],
                      ).withTouchResonance(
                        onTap: () {
                          if (!isLoggedIn) {
                            return;
                          }
                          if (currentUser != null) {
                            if (liked) {
                              communityChronicle.unlikeCommunity(
                                currentUser.id,
                                communityId,
                              );
                            } else {
                              communityChronicle.likeCommunity(
                                currentUser.id,
                                communityId,
                              );
                            }
                          }
                        },
                      ),
                      20.w.boxWidth,
                      // 评论数量
                      Row(
                        children: [
                          Image.asset(
                            'assets/images/message-text.png',
                            width: 18.w,
                            height: 18.w,
                            color: RazeConstants.black,
                          ),
                          6.w.boxWidth,
                          Text('$commentCount')
                              .applyTypeSize(14.sp)
                              .applyTypeColor(RazeConstants.black)
                              .applyNotoSans(weight: FontWeight.w600),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ).withRightBottomShadow(thickness: 1.5);
    });
  }
}
